#include "bflb_mtimer.h"
#include "board.h"
#include "bflb_uart.h"
#include "bflb_gpio.h"
#include "FreeRTOS.h"
#include "task.h"
#include "math.h"

#define DBG_TAG "MAIN"
#include "log.h"

struct bflb_device_s *gpio;
struct bflb_device_s *rd03e;
uint8_t UART_RECEIVE_BUFFER[5];

void _rd03eTask(void* pvParameters){
    int index = 0;
    int data_count = 5;
    int status = 0;
    while (1)
    {
         int ch = bflb_uart_getchar(rd03e);
         if(ch!=-1){
            if(ch == 0xAA){
                memset(UART_RECEIVE_BUFFER,0 , sizeof(UART_RECEIVE_BUFFER));
                index = 0;
            }
            if(index < data_count){
                UART_RECEIVE_BUFFER[index++] = ch;
                if(ch == 0x55){
                    // for (size_t i = 0; i < sizeof(UART_RECEIVE_BUFFER); i++)
                    // {
                    //     printf("0x%02x ", UART_RECEIVE_BUFFER[i]);
                    // }

                    if(UART_RECEIVE_BUFFER[3] == 0x01){
                      printf("触发了手势\r\n");   
                      if(status==0){
                        status = 1;
                        bflb_gpio_set(gpio, GPIO_PIN_14);
                      }else{
                        status = 0;
                        bflb_gpio_reset(gpio, GPIO_PIN_14);
                      }
                    }
                    // printf("\r\n");
                }
            }
         }
       vTaskDelay(1);
    }
    
}

int main(void)
{
    board_init();

    gpio = bflb_device_get_by_name("gpio");
    bflb_gpio_uart_init(gpio, GPIO_PIN_23, GPIO_UART_FUNC_UART1_TX);
    bflb_gpio_uart_init(gpio, GPIO_PIN_24, GPIO_UART_FUNC_UART1_RX);
    bflb_gpio_init(gpio, GPIO_PIN_14, GPIO_OUTPUT | GPIO_PULLUP | GPIO_SMT_EN | GPIO_DRV_0);
    bflb_gpio_reset(gpio, GPIO_PIN_14);

    rd03e = bflb_device_get_by_name("uart1");

    struct bflb_uart_config_s conf = {
        .baudrate = 256000,
        .data_bits = UART_DATA_BITS_8,
        .stop_bits = UART_STOP_BITS_1,
        .parity = UART_PARITY_NONE,
        .flow_ctrl = UART_FLOWCTRL_NONE,
        .rx_fifo_threshold = 7,
        .tx_fifo_threshold = 7
    };
    bflb_uart_init(rd03e, &conf);

    xTaskCreate(_rd03eTask, (char*)"rd03e", 1024, NULL, 1, NULL);
    vTaskStartScheduler();

    while (1) {
     
    }
}
